import React , { useEffect, useState }  from 'react';
import type { ColumnsType } from "antd/es/table";

import {
  Input,
  Button,
  Table,
  Modal,
  message,
  Form,
  Space,
  Select,
  Tooltip
} from "antd";
import pwdServices from '@/services/pwd';
import { ShowIcon } from '@/icon';
import { ENCRYPT_TYPES } from '@/constants';
import PowerShow from './PowerShow';

const { pagePasswordApi,createPasswordApi ,deletePasswordApi,viewPasswordApi,rsaKeyApi} =  pwdServices.KeePassController;


// 初始化弹窗加载信息 / 实体
let addModalData={
  title:"",
  isShow:false
}
let inputValue=''
let pwdModalData={
  isPwdShow:false,
  id:0
}
let secret=""//密钥

const PWD: React.FC = () => {

  const [rowData, setRowData] = useState<KeePassVO[]>();
  const [pagination, setPagination] = useState({});
  const [addModal, setAddModal] = useState(addModalData);
  const [pwdModal,setPwdModal] =useState(pwdModalData)
  const [cleartextPwd,setCleartextPwd] =useState('')
  const [rsaKeys, setRsaKeys] = useState({ publicKey: '', privateKey: '' });
  const [isRsaModalVisible, setIsRsaModalVisible] = useState(false);


// 新增数据
  const [form] = Form.useForm();
  const [initData] = useState<CreateKeePass>({
    groupings: "",
    title: "",
    username: "",
    password: "",
    secret: "",
    url: "",
    remark: "",
    encryptTypeStr: ENCRYPT_TYPES.AES,
    encryptCount: 0,
  });

  useEffect(() => {
    dataListApi({
      title:'',
      pageSort: {
        orderBy: "id",
        orderDesc: 0,
        pageIndex: 1,
        pageSize: 10,
      },
    });
  }, []);

  // 列表参数接口
  async function dataListApi(params: KeePassPage) {
    const response = await pagePasswordApi(params);
    if (!response?.data) {
      return;
    }
    const { currentPage, pageSize, total, rows } = response.data;
    setPagination({
      defaultCurrent: 1,
      defaultPageSize: 10,
      // hideOnSinglePage: true,
      current: currentPage,
      pageSize: pageSize,
      total: total,
      onChange: (page:number, pageSize:number) => {
        dataListApi({
          pageSort: {
            orderBy: "id",
            orderDesc: 0,
            pageIndex: page,
            pageSize: pageSize,
          },
        });
      },
    });
  // 列表参数
  const data: KeePassVO[] = [];
  Object.entries(rows || []).forEach(([k, v]) => {
    if (typeof v === 'object' && v !== null) {
      data.push(v as KeePassVO);
    }
  });
  setRowData(data);
};

const handleSearch=async (values: any)=>{
  dataListApi({
    title:values,
    groupings: values,
    pageSort: {
      orderBy: "id",
      orderDesc: 0,
      pageIndex: 1,
      pageSize: 10,
    },
  });
}

// 新增
const handleAdd=()=>{
  setAddModal({
    title:"新增",
    isShow:true
  })
}

// 获取加密用的公私钥
const handleGetRsaKeys = async () => {
  try {
    const {success,data,message: messageSS} = await rsaKeyApi(); 
    if (success) {
      message.success(messageSS);
      // console.log('公钥:', data?.publicKey);
      // console.log('私钥:', data?.privateKey);
      setRsaKeys({ 
        publicKey: data?.publicKey || '', 
        privateKey: data?.privateKey || '' 
      });
      setIsRsaModalVisible(true);
    } 
  } catch (error) {
    // message.error('请求失败');
  }
};

// 下载加密用的公私钥
const downloadRsaKeys = () => {
  const content = `公钥:\n${rsaKeys.publicKey}\n\n私钥:\n${rsaKeys.privateKey}`;
  const blob = new Blob([content], { type: 'text/plain' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = 'rsa_keys.txt';
  a.click();
  URL.revokeObjectURL(url);
};


// 关闭弹窗
const handleCancel=()=>{
  setAddModal({
    title:"",
    isShow:false
  })
}
// 新增确认
const onFinish = async (values: CreateKeePass) => {
  try {
    await createPasswordApi(values).then((res) => {
      handleCancel()
      dataListApi({})
    });
  } catch (error: any) {
    // message.error(error.message) // 全局有message
    // 错误处理
  }
};
const onFinishFailed = () => {
  message.error("Submit failed!");
};
// 查询input框
const changeInput =(event:any)=>{
  inputValue = event.target.value
}
// 表头
const columns: ColumnsType<KeePassVO> = [
  {
    title: "分组",
    dataIndex: "groupings",
    key: "groupings",
  },
  {
    title: "用户名",
    dataIndex: "username",
    key: "username",
  },
  {
    title: "密码标题",
    dataIndex: "title",
    key: "title",
  },
  // {
  //   title: "加密方式",
  //   dataIndex: "encryptType",
  //   key: "encryptType",
  // },
  {
    title: "密文",
    dataIndex: "password",
    key: "password",
    render: (_, {password, id }) => (
      <Tooltip title={password}>
      <span
        style={{
            overflow: 'hidden',
            textOverflow: 'ellipsis',
            maxWidth: '100px',  // 控制显示的最大宽度
            display: 'inline-block',
            whiteSpace: 'nowrap' // 防止文本换行
          }}
        >
            <Button  type="text" icon={<ShowIcon />}  onClick={() => handleShowPwd(id)}> {password}</Button>
        </span>
      </Tooltip>
    ),
  },
  {
    title: "地址连接",
    dataIndex: "url",
    key: "url",
  },
  {
    title: "备注",
    dataIndex: "remark",
    key: "remark",
    render: (_, {remark}) => (
      <Tooltip title={remark}>
      <span
        style={{
            overflow: 'hidden',
            textOverflow: 'ellipsis',
            maxWidth: '150px',  // 控制显示的最大宽度
            display: 'inline-block',
            whiteSpace: 'nowrap' // 防止文本换行
          }}
        >
             {remark}
        </span>
      </Tooltip>
    ),
  },
  {
    title: "状态",
    key: "status",
    dataIndex: "status",
    render: (text) => {
      let color;
      let showText;
      switch (text) {
        case 'VALID':
          color = 'green';
          showText = '有效';
          break;
        case 'RECYCLED':
          color = 'red';
          showText = '回收站';
          break;
        default:
          color = 'black';
          showText = text;
          break;
      }
      return <span style={{ color }}>{showText}</span>;
    },
  },
  {
    title: '操作',
    key: 'operaion',
    render: (row, record) => (
      <Space size="middle">
          {/* <a className="action-link" onClick={() => handleEdit(row)}>修改</a> */}
          <a className="action-link" onClick={() => handleDelete(row, record.id)}>删除</a>
      </Space>
  ),
  },
];
// 删除操作
const handleDelete = (row:KeePassVO, id:number) => {
  console.log(row.status)
  let text ='删除会放到回收站'
  if(row.status==='RECYCLED'){
    text ='删除会直接删了'
  }
  Modal.confirm({
      title: '删除密码',
      content: text,
      onOk: () => {
        deletePasswordApi(id).then((res) => {
          if(res.success){
            message.success('删除成功!')
           dataListApi({})
          }
        });
      }
  })
}
// 查看密码操作
const handleShowPwd =(id:number)=>{
  setPwdModal({
    isPwdShow:true,
    id:id
  })
}
const changeSecret =(event:any)=>{
  secret =event.target.value
}
const handlePwdOk = async() => {
  try {
    await viewPasswordApi(pwdModal.id,secret).then((res) => {
      if(res.success){
        setCleartextPwd(res.data || '');
      }
    });
  } catch (error: any) {
    // 错误处理 
  }
};

const handlePwdCancel = () => {
  setPwdModal({
    isPwdShow:false,
    id:0
  })
  setCleartextPwd('')
};



const headerStyle = { display: 'flex',padding:'20px'}
  return (
    <div>
      <div style={headerStyle}>
       <Input placeholder="请输入密码标题/分组" onChange={changeInput}  style={{width:'50%'}} />
       <Button type="default" style={{margin:'0 20px 0 10px'}} onClick={() => handleSearch(inputValue)}> 查询 </Button>
       <Button type="primary" style={{margin:'0 20px 0 10px'}} onClick={() => handleAdd()}> 创建 </Button>
       <Button type="primary" onClick={() => handleGetRsaKeys()}>获取RSA公私钥</Button>
     </div>
     <div>
      <Table columns={columns} dataSource={rowData} pagination={pagination} scroll={{ y: '100%' }} />
     </div>
     {/* 新增密码弹窗 */}
     <Modal
        title={addModal.title}
        open={addModal.isShow}
        closable={false}
        footer={null}
    >
        <Form
         form={form}
         labelCol={{ span: 6 }}
         wrapperCol={{ span: 18 }}
         initialValues={initData}
         onFinish={onFinish}
         onFinishFailed={onFinishFailed}
         autoComplete="off"
        >
          <Form.Item label="分组" name="groupings" >
            <Input placeholder="请输入分组名" id="groupings"/>
          </Form.Item>
          <Form.Item label="密码标题" name="title"  rules={[{ required: true, message: '请输入密码标题!' }]}>
            <Input placeholder="请输入密码标题" id="title"/>
          </Form.Item>
          <Form.Item label="用户名" name="username"  rules={[{ required: true, message: '请输入用户名!' }]} >
            <Input placeholder="请输入用户名" id="username"/>
          </Form.Item>
          <Form.Item label="密码" name="password"  rules={[{ required: true, message: '请输入密码!' }]}>
            <Input placeholder="请输入密码" id="password"/>
          </Form.Item>
          <Form.Item label="加密方式" name="encryptTypeStr" rules={[{ required: true, message: '请输入加密方式!' }]}>
            <Select placeholder="请选择加密方式">
              {Object.entries(ENCRYPT_TYPES).map(([key, value]) => (
                <Select.Option key={key} value={value}>{value}</Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item label="密钥" name="secret"  help="对称加密用加密时的密钥，非对称用公钥"  rules={[{ required: true, message: '请输入密钥!' }]}>
            <Input placeholder="请输入密钥" id="secret"/>
          </Form.Item>
          {/* <Form.Item label="加密次数[还没启用]" name="encryptCount" rules={[{ required: true, message: '请输入加密次数!' }]}>
            <InputNumber placeholder="请输入加密次数" min={0} max={5}  />
          </Form.Item> */}
          <Form.Item label="密码相关地址" name="url" >
            <Input placeholder="请输入密码相关地址" id="url"/>
          </Form.Item>
          <Form.Item label="备注" name="remark" >
            <Input placeholder="请输入备注" id="remark"/>
          </Form.Item>
          <Form.Item>
              <Button type="primary" htmlType="submit" style={{margin:'0 50px'}} >确认</Button>
              <Button  onClick={() => handleCancel()} >取消</Button>
          </Form.Item>
       </Form>
    </Modal>
    {/* 查看密码弹窗 */}
    <Modal
     title="私钥"
     open={pwdModal.isPwdShow}
     closable={false}
     footer={null}
    >
       <Input placeholder="请输入密钥/RSA私钥" onChange={changeSecret} />
       <PowerShow cleartextPwd={cleartextPwd}></PowerShow>
       {/* bug: 浏览器记录的历史值必须点一下能直接使用 */}
       <Button type="primary"  onClick={() => handlePwdOk()} style={{margin:'20px 80px'}} >确认</Button>
       <Button onClick={() => handlePwdCancel()} >取消</Button>
    </Modal>

    <Modal
      title="RSA公私钥"
      open={isRsaModalVisible}
      onCancel={() => setIsRsaModalVisible(false)}
      footer={null}
      centered
    >
      <p>公钥:</p>
      <textarea value={rsaKeys.publicKey} readOnly style={{ width: '100%', height: '100px' }} />
      <p>私钥:</p>
      <textarea value={rsaKeys.privateKey} readOnly style={{ width: '100%', height: '100px' }} />
      <Button type="primary" onClick={downloadRsaKeys} style={{ marginTop: '10px' }}>
        下载公私钥
      </Button>
    </Modal>
    </div>
  );
}

export default PWD;
